package com.action.wx.order;

import com.bean.*;
import com.common.*;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.interceptor.CheckWxLogin;
import com.service.addressbook.AddressBookService;
import com.service.dis.DisCompanyService;
import com.service.member.MbAccountService;
import com.service.member.MemberService;
import com.service.order.OrderService;
import com.service.product.ProductService;
import com.service.tag.TagService;
import com.util.Config;
import com.util.KdniaoApi;
import com.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/9/12.
 */
@Controller
@RequestMapping("wx/order")
public class WxOrderAction extends BaseAction {

    @Autowired
    private ProductService productService;

    @Autowired
    private  MbAccountService mbAccountService;

    @Autowired
    private AddressBookService  addressBookService;

    @Autowired
    private TagService tagService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private DisCompanyService disCompanyService;

    @ResponseBody
    @RequestMapping("checkDraPrm")
    public String checkDraPrm(ModelAndJson modelMap,Integer mid) {
        try {
            HttpSession session = this.getSession();
            Member member=memberService.selectByPrimaryKey(mid);
           if(member.getIsactive()==1) {
               modelMap.setFalse("error", "会员已经激活");
               return modelMap.toString();
           }
        }catch (Exception e){
            modelMap.setFalse("error","操作出现异常");
            return modelMap.toString();
        }
        return modelMap.toString();
    }

    @ResponseBody
    @RequestMapping("setOrderSession")
    public String setOrderSession(ModelAndJson modelMap,Integer pid) {
        try {
            HttpSession session = this.getSession();
            Product draProduct = productService.selectByPrimaryKey(pid);
            ProductVo proVo=new ProductVo();
            BeanUtils.copyProperties(draProduct,proVo);
            proVo.setProNum(1);
            List<ProductVo> draList=new ArrayList<ProductVo>();
            draList.add(proVo);
            session.setAttribute(SystemConfig.draProListSession,draList);
            session.setAttribute(SystemConfig.orderAmountSession,proVo.getPrice());
            BigDecimal orderAmount=draProduct.getPrice();
            session.setAttribute(SystemConfig.orderAmountSession,orderAmount);
        }catch (Exception e){
            modelMap.setFalse("error","操作出现异常");
            return modelMap.toString();
        }
        modelMap.setTrue("已经加入购物车");
        return modelMap.toString();
    }

    @ResponseBody
    @RequestMapping("addCart")
    public String addCart(ModelAndJson modelMap,Integer pid  , HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        Integer count =Integer.parseInt(request.getParameter("count"));
        ObjectMapper objectMapper = new ObjectMapper() ;
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        BuyerCart buyerCart = (BuyerCart) session.getAttribute(SystemConfig.CartItemSession) ;
//        Cookie[] cookies = request.getCookies();
//        if(null != cookies && cookies.length> 0){
//            for (Cookie cookie : cookies){
//                if("pid".equals(cookie.getName())){
//                    //将购物车对象 与 json 字符串互转
//                    buyerCart = objectMapper.readValue(cookie.getValue() ,BuyerCart.class);
//                    break;
//                }
//            }
//        }
        //如果cookies中没有购物车 则创建一个购物车对象
        if(null == buyerCart){
            buyerCart = new BuyerCart() ;
        }
        //将当期商品添加到购物车中
        if(null != pid && null != count){
            Product product = productService.selectByPrimaryKey(pid);
            BuyerItem buyerItem = new BuyerItem() ;
            buyerItem.setProduct(product);
            buyerItem.setAmount(count);
            buyerCart.addItem(buyerItem);
            session.setAttribute(SystemConfig.CartItemSession ,buyerCart);
            modelMap.setTrue("已经加入购物车");
            return modelMap.toString();
        }
        return null ;
    }

    @RequestMapping("cartlist")
    public ModelAndView cartlist(Integer ot ,ModelMap modelMap) {
        HashMap<String, Object> paraMap = new HashMap<>();
        HttpSession session = this.getSession();
        Integer cid=(Integer)session.getAttribute(SystemConfig.CityIdSession);
        paraMap.put("cid",cid);
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        if(cid == null || mid == null){
            String autoLoginUrl= Config.getString("login.index");
            modelMap.put("autoLoginUrl",autoLoginUrl);
            return new ModelAndView("/wx/common/login_error", modelMap);
        }
        if(mid!=null){
            Mb_account mc = mbAccountService.selectByMemberId(mid);
            paraMap.put("mc",mc);
            List<AddressVo> addressList = addressBookService.selectByMemberId(mid);
            paraMap.put("addressList",addressList);
        }else{
            return new ModelAndView("redirect:/wx/index.htm", paraMap);
        }
        paraMap.put("mid",mid);
        BuyerCart buyerCart = (BuyerCart) session.getAttribute(SystemConfig.CartItemSession);
        AddressVo orderAddr = (AddressVo) session.getAttribute(SystemConfig.orderAddressSession);
        List<Tag> tagList=tagService.findByParentId(0);
        paraMap.put("ItemList",buyerCart == null? null : buyerCart.getItems());
        paraMap.put("orderAmount",buyerCart == null? null :buyerCart.getTotalPrice());
        paraMap.put("orderAddr",orderAddr);
        paraMap.put("orderAddrId",orderAddr!=null?orderAddr.getId():null);
        paraMap.put("tagList",tagList);
        paraMap.put("orderType",ot);
        return new ModelAndView("/wx/order/order_cart", paraMap);
    }
    @RequestMapping("orderEdit")
    public ModelAndView orderEdit(Integer ot) {
            HashMap<String, Object> paraMap = new HashMap<>();
            HttpSession session = this.getSession();
            Integer cid=(Integer)session.getAttribute(SystemConfig.CityIdSession);
            paraMap.put("cid",cid);
            Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
            /*调试内容开始*/
            //mid=4;
             /*调试内容结束*/
            if(mid!=null){
                Mb_account mc = mbAccountService.selectByMemberId(mid);
                paraMap.put("mc",mc);
                List<AddressVo> addressList = addressBookService.selectByMemberId(mid);
                paraMap.put("addressList",addressList);
            }else{
                return new ModelAndView("redirect:/wx/index.htm", paraMap);
            }
            paraMap.put("mid",mid);
            List<ProductVo> draProList = (List<ProductVo>) session.getAttribute(SystemConfig.draProListSession);
            BigDecimal orderAmount = (BigDecimal)session.getAttribute(SystemConfig.orderAmountSession);
            AddressVo orderAddr = (AddressVo) session.getAttribute(SystemConfig.orderAddressSession);

            /*调试内容开始*/
            /*Product draProduct = productService.selectByPrimaryKey(1);
            ProductVo proVo=new ProductVo();
            BeanUtils.copyProperties(draProduct,proVo);
            proVo.setProNum(1);
            draProList=new ArrayList<>();
            draProList.add(proVo);*/
            /*调试内容结束*/

            List<Tag> tagList=tagService.findByParentId(0);

            paraMap.put("draProList",draProList);
            paraMap.put("orderAmount",orderAmount);
            paraMap.put("orderAddr",orderAddr);
            paraMap.put("orderAddrId",orderAddr!=null?orderAddr.getId():null);
            paraMap.put("tagList",tagList);
            paraMap.put("orderType",ot);
        return new ModelAndView("/wx/order/order_edit", paraMap);
    }

    /**
     * 创建订单
     * @param modelMap
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping("createOrder")
    public String createOrder(ModelAndJson modelMap,OrderVo order ) {
        try {
            HttpSession session = this.getSession();
            //获取session中的商品信息
            if(order.getOrderType()==1||order.getOrderType()==4){
                List<ProductVo> draProList = (List<ProductVo>)session.getAttribute(SystemConfig.draProListSession);
                order.setProList(draProList);
            }
            modelMap = orderService.createOrder(order);
        }catch (Exception e){
            e.getStackTrace();
            modelMap.setFalse("error","操作出现异常");
            return modelMap.toString();
        }
        return modelMap.toString();
    }


    /**
     * 订单列表
     * @param ot  订单类型
     * @param s   订单状态
     * @return
     */
    @CheckWxLogin(name = "LoginCheck", failed = "/wx/loginError.htm")
    @RequestMapping("orderList")
    public ModelAndView orderList(ModelMap modelMap, Integer ot, Integer s,Integer pageNum, Integer pageSize) {
        HttpSession session = this.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);

        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;

        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        paraMap.put("ordertype",ot);
        paraMap.put("orderstatus",s);
        Page page = orderService.findMemberOrdersByPage(pageNum,pageSize,paraMap);
        modelMap.put("page",page);
        modelMap.put("totalPage",page.getPages());
        modelMap.put("mid",mid);
        modelMap.put("ordertype",ot);
        modelMap.put("orderstatus",s);
        modelMap.put("pageNum",pageNum);
        modelMap.put("pageSize",pageSize);
        if(ot==2){
            return new ModelAndView("/wx/order/order_list_charge", modelMap);
        }else if(ot==3){
            return new ModelAndView("/wx/order/order_list_get", modelMap);
        }
        return new ModelAndView("/wx/order/order_list", modelMap);
    }

    /**
     * 订单列表分页数据
     * @param modelMap
     * @param ot
     * @param mid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("orderListData")
    public String orderListData(ModelAndJson modelMap, Integer ot,Integer mid,Integer s, Integer pageNum, Integer pageSize) {
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("mid",mid);
        pageNum=pageNum==null?0:pageNum;
        pageSize=pageSize==null?10:pageSize;
        paraMap.put("ordertype",ot);
        modelMap.put("orderstatus",s);
        Page page = orderService.findMemberOrdersByPage(pageNum,pageSize,paraMap);
        modelMap.put("page",page);
        modelMap.setTrue("");
        return modelMap.toString();
    }

    /**
     * 物流信息
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping("express")
    public ModelAndView express(HttpServletRequest request, ModelMap modelMap, String disNo, Integer companyName) {
        if (StringUtil.isNotEmpty(disNo) && companyName!=null) {
            try {
                Dis_company dc = disCompanyService.selectByPrimaryKey(companyName);
                Express e = KdniaoApi.instance().getOrderTraces(dc.getCode(), disNo);
                modelMap.put("express", e);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ModelAndView("/wx/order/express", modelMap);
    }

}
